#!/usr/bin/env node

/**
 * Minecraft面板清理脚本
 * 用于清理临时文件、日志文件和无用的数据
 */

const fs = require('fs');
const path = require('path');
const os = require('os');

console.log('==========================================');
console.log('  Minecraft面板清理脚本');
console.log('==========================================');
console.log();

// 配置
const config = {
    tempDir: path.join(__dirname, '..', 'temp'),
    logsDir: path.join(__dirname, '..', 'logs'),
    uploadsDir: path.join(__dirname, '..', 'public', 'uploads'),
    backupsDir: path.join(__dirname, '..', 'backups'),
    nodeModulesDir: path.join(__dirname, '..', 'node_modules'),
    packageLockFile: path.join(__dirname, '..', 'package-lock.json'),
    npmCache: path.join(os.homedir(), '.npm'),
    dockerCache: '/var/lib/docker'
};

// 获取目录大小
function getDirectorySize(dirPath) {
    let totalSize = 0;
    
    if (fs.existsSync(dirPath)) {
        const files = fs.readdirSync(dirPath);
        
        files.forEach(file => {
            const filePath = path.join(dirPath, file);
            const stats = fs.statSync(filePath);
            
            if (stats.isDirectory()) {
                totalSize += getDirectorySize(filePath);
            } else {
                totalSize += stats.size;
            }
        });
    }
    
    return totalSize;
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 清理临时文件
function cleanTempFiles() {
    console.log('🗑️  清理临时文件...');
    
    if (fs.existsSync(config.tempDir)) {
        const size = getDirectorySize(config.tempDir);
        fs.rmSync(config.tempDir, { recursive: true, force: true });
        fs.mkdirSync(config.tempDir, { recursive: true });
        console.log(`   ✅ 清理临时文件: ${formatFileSize(size)}`);
    } else {
        console.log('   ℹ️  临时目录不存在');
    }
}

// 清理日志文件
function cleanLogFiles(keepDays = 7) {
    console.log('📄 清理日志文件...');
    
    if (fs.existsSync(config.logsDir)) {
        const files = fs.readdirSync(config.logsDir);
        const cutoffTime = new Date(Date.now() - keepDays * 24 * 60 * 60 * 1000);
        let totalSize = 0;
        let cleanedCount = 0;
        
        files.forEach(file => {
            const filePath = path.join(config.logsDir, file);
            const stats = fs.statSync(filePath);
            
            if (stats.isFile() && stats.mtime < cutoffTime) {
                totalSize += stats.size;
                fs.unlinkSync(filePath);
                cleanedCount++;
            }
        });
        
        console.log(`   ✅ 清理日志文件: ${cleanedCount}个文件, ${formatFileSize(totalSize)}`);
    } else {
        console.log('   ℹ️  日志目录不存在');
    }
}

// 清理上传文件
function cleanUploadFiles(keepDays = 30) {
    console.log('📤 清理上传文件...');
    
    if (fs.existsSync(config.uploadsDir)) {
        const files = fs.readdirSync(config.uploadsDir);
        const cutoffTime = new Date(Date.now() - keepDays * 24 * 60 * 60 * 1000);
        let totalSize = 0;
        let cleanedCount = 0;
        
        files.forEach(file => {
            const filePath = path.join(config.uploadsDir, file);
            const stats = fs.statSync(filePath);
            
            if (stats.isFile() && stats.mtime < cutoffTime) {
                totalSize += stats.size;
                fs.unlinkSync(filePath);
                cleanedCount++;
            }
        });
        
        console.log(`   ✅ 清理上传文件: ${cleanedCount}个文件, ${formatFileSize(totalSize)}`);
    } else {
        console.log('   ℹ️  上传目录不存在');
    }
}

// 清理备份文件
function cleanBackupFiles(keepCount = 10) {
    console.log('💾 清理备份文件...');
    
    if (fs.existsSync(config.backupsDir)) {
        const files = fs.readdirSync(config.backupsDir);
        const backupFiles = files.filter(file => 
            file.startsWith('minecraft-panel-backup-') && 
            (file.endsWith('.sqlite') || file.endsWith('.zip'))
        );
        
        if (backupFiles.length > keepCount) {
            // 按修改时间排序
            backupFiles.sort((a, b) => {
                const statA = fs.statSync(path.join(config.backupsDir, a));
                const statB = fs.statSync(path.join(config.backupsDir, b));
                return statB.mtime - statA.mtime;
            });
            
            // 删除最旧的备份
            const filesToDelete = backupFiles.slice(keepCount);
            let totalSize = 0;
            
            filesToDelete.forEach(file => {
                const filePath = path.join(config.backupsDir, file);
                const stats = fs.statSync(filePath);
                totalSize += stats.size;
                fs.unlinkSync(filePath);
            });
            
            console.log(`   ✅ 清理备份文件: ${filesToDelete.length}个文件, ${formatFileSize(totalSize)}`);
        } else {
            console.log(`   ℹ️  备份文件数量正常 (${backupFiles.length}/${keepCount})`);
        }
    } else {
        console.log('   ℹ️  备份目录不存在');
    }
}

// 清理node_modules
function cleanNodeModules() {
    console.log('📦 清理node_modules...');
    
    if (fs.existsSync(config.nodeModulesDir)) {
        const size = getDirectorySize(config.nodeModulesDir);
        fs.rmSync(config.nodeModulesDir, { recursive: true, force: true });
        console.log(`   ✅ 清理node_modules: ${formatFileSize(size)}`);
        console.log('   💡 运行 npm install 重新安装依赖');
    } else {
        console.log('   ℹ️  node_modules目录不存在');
    }
}

// 清理package-lock.json
function cleanPackageLock() {
    console.log('🔒 清理package-lock.json...');
    
    if (fs.existsSync(config.packageLockFile)) {
        const stats = fs.statSync(config.packageLockFile);
        fs.unlinkSync(config.packageLockFile);
        console.log(`   ✅ 清理package-lock.json: ${formatFileSize(stats.size)}`);
        console.log('   💡 运行 npm install 重新生成');
    } else {
        console.log('   ℹ️  package-lock.json文件不存在');
    }
}

// 清理npm缓存
function cleanNpmCache() {
    console.log('🗃️  清理npm缓存...');
    
    if (fs.existsSync(config.npmCache)) {
        const { execSync } = require('child_process');
        try {
            execSync('npm cache clean --force', { stdio: 'pipe' });
            console.log('   ✅ npm缓存清理完成');
        } catch (error) {
            console.log('   ⚠️  npm缓存清理失败');
        }
    } else {
        console.log('   ℹ️  npm缓存目录不存在');
    }
}

// 清理Docker缓存
function cleanDockerCache() {
    console.log('🐳 清理Docker缓存...');
    
    const { execSync } = require('child_process');
    
    try {
        // 检查Docker是否运行
        execSync('docker info', { stdio: 'pipe' });
        
        // 清理未使用的Docker对象
        execSync('docker system prune -f', { stdio: 'pipe' });
        console.log('   ✅ Docker缓存清理完成');
    } catch (error) {
        console.log('   ℹ️  Docker未运行或不可用');
    }
}

// 显示磁盘使用情况
function showDiskUsage() {
    console.log('💽 磁盘使用情况:');
    
    const dirs = [
        { name: '项目根目录', path: path.join(__dirname, '..') },
        { name: '日志目录', path: config.logsDir },
        { name: '上传目录', path: config.uploadsDir },
        { name: '备份目录', path: config.backupsDir },
        { name: '临时目录', path: config.tempDir }
    ];
    
    dirs.forEach(dir => {
        if (fs.existsSync(dir.path)) {
            const size = getDirectorySize(dir.path);
            console.log(`   ${dir.name}: ${formatFileSize(size)}`);
        }
    });
    
    console.log();
}

// 显示系统信息
function showSystemInfo() {
    console.log('🖥️  系统信息:');
    console.log(`   平台: ${os.platform()}`);
    console.log(`   架构: ${os.arch()}`);
    console.log(`   内存总量: ${formatFileSize(os.totalmem())}`);
    console.log(`   内存空闲: ${formatFileSize(os.freemem())}`);
    console.log(`   CPU核心: ${os.cpus().length}`);
    console.log();
}

// 主清理函数
function performCleanup(options = {}) {
    const {
        cleanTemp = true,
        cleanLogs = true,
        cleanUploads = true,
        cleanBackups = true,
        cleanNodeModules = false,
        cleanPackageLock = false,
        cleanNpmCache = false,
        cleanDockerCache = false,
        showInfo = true
    } = options;

    console.log('🚀 开始清理...');
    console.log();

    if (showInfo) {
        showSystemInfo();
        showDiskUsage();
    }

    if (cleanTemp) cleanTempFiles();
    if (cleanLogs) cleanLogFiles();
    if (cleanUploads) cleanUploadFiles();
    if (cleanBackups) cleanBackupFiles();
    if (cleanNodeModules) cleanNodeModules();
    if (cleanPackageLock) cleanPackageLock();
    if (cleanNpmCache) cleanNpmCache();
    if (cleanDockerCache) cleanDockerCache();

    console.log('==========================================');
    console.log('  ✅ 清理完成！');
    console.log('==========================================');
    console.log();
}

// 命令行参数处理
function handleCommandLineArgs() {
    const args = process.argv.slice(2);
    
    if (args.length === 0) {
        // 默认清理
        performCleanup();
    } else if (args[0] === 'all') {
        // 全面清理
        performCleanup({
            cleanTemp: true,
            cleanLogs: true,
            cleanUploads: true,
            cleanBackups: true,
            cleanNodeModules: true,
            cleanPackageLock: true,
            cleanNpmCache: true,
            cleanDockerCache: true,
            showInfo: true
        });
    } else if (args[0] === 'logs') {
        // 只清理日志
        performCleanup({
            cleanLogs: true,
            showInfo: false
        });
    } else if (args[0] === 'temp') {
        // 只清理临时文件
        performCleanup({
            cleanTemp: true,
            showInfo: false
        });
    } else if (args[0] === 'uploads') {
        // 只清理上传文件
        performCleanup({
            cleanUploads: true,
            showInfo: false
        });
    } else if (args[0] === 'backups') {
        // 只清理备份文件
        performCleanup({
            cleanBackups: true,
            showInfo: false
        });
    } else if (args[0] === 'npm') {
        // 清理npm相关
        performCleanup({
            cleanNodeModules: true,
            cleanPackageLock: true,
            cleanNpmCache: true,
            showInfo: false
        });
    } else if (args[0] === 'docker') {
        // 清理Docker缓存
        performCleanup({
            cleanDockerCache: true,
            showInfo: false
        });
    } else if (args[0] === 'info') {
        // 只显示信息
        showSystemInfo();
        showDiskUsage();
    } else {
        console.log('用法:');
        console.log('  node scripts/clean.js          - 执行默认清理');
        console.log('  node scripts/clean.js all       - 全面清理');
        console.log('  node scripts/clean.js logs      - 清理日志文件');
        console.log('  node scripts/clean.js temp      - 清理临时文件');
        console.log('  node scripts/clean.js uploads   - 清理上传文件');
        console.log('  node scripts/clean.js backups   - 清理备份文件');
        console.log('  node scripts/clean.js npm       - 清理npm相关');
        console.log('  node scripts/clean.js docker    - 清理Docker缓存');
        console.log('  node scripts/clean.js info      - 显示系统信息');
        process.exit(1);
    }
}

// 运行脚本
handleCommandLineArgs();